<?php
class User extends My_Model {
	var	$_table			= 'users';
	var	$_prkey			= 'id';
    function __construct()
    {
        parent::My_Model();
    }

	function findByUserName($username=null){
		$username = empty($username) ? $this->_data['username'] : $username;
		if(!empty($username)){
			$where = array('username'=>$username);
			$query = $this->db->get_where($this->_table,$where);
			$rs = $query->row_array();
			return $rs;
		}
		return null;
	}
	
	function findByUserId($userId=0){
		$userId = empty($userId) ? $this->_data['id'] : $userId;
		
		if(!empty($userId)){
			$where = array('id'=>$userId);
			$query = $this->db->get_where($this->_table,$where);
			$rs = $query->result_array();
			return $rs[0];
		} 
		return null;
	} 
	
	function findAll(){
		$query = $this->db->get($this->_table);
		$rs = $query->result_array();
		return $rs;
	}

	/**
	 * 根据用户名密码登陆
	 * 
	 * @param string $user
	 * @param string $pwd
	 * @return mix $user or false
	 */
	function doLogin($user,$pwd){
		$user	= $this->findByUserName($user);
		//用户名不存在！
		if(empty($user)){
			$this->_error = 'error_user_noexists';
			return false;
		}
		if($user['password']!=crypt(trim($pwd),$user['salt'])){
			$this->_error = 'error_pwd_wrong';
			return false;
		}
		if($user['is_locked']){
			$this->_error = 'error_user_islocked';
			return false;
		}
		return $user;
	}

	function save($user){
		if(isset($user['password'])){
			$this->load->helper('rndcode');
			$user['salt']	=  random(6);
			$user['password'] = crypt($user['password'],$user['salt']);
		}
		if(isset($user['username'])){
			$users = $this->findByUserName($user['username']);
			if(!empty($users)&&$users['id']!=$user['id']){
				$this->_error = "error_user_exists";
				return false;
			}
		}
		return parent::save($user);
	}
}
?>